<template>
  <div class="page-box">
    <el-card class="page-box-card">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        label-width="88px"
        inline
      >
        <el-form-item label="变量名称" prop="param.text">
          <el-input
            v-model="queryParams.param.text"
            placeholder="请输入变量名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="变量CODE" prop="param.code">
          <el-input
            v-model="queryParams.param.code"
            placeholder="请输入变量CODE"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="变量标签" prop="param.tagIdList">
          <el-select
            style="width: 240px"
            multiple
            v-model="queryParams.param.tagIdList"
            placeholder="请选择变量标签"
          >
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['definition:class:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleEdit"
            v-hasPermi="['definition:class:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['definition:class:delete']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            v-hasPermi="['definition:class:upload']"
            @click="handleImport"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            v-hasPermi="['definition:class:download']"
            @click="downloadData"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed />
        <el-table-column
          prop="name"
          label="变量名称"
          width="180"
          align="center"
          fixed
        >
        </el-table-column>
        <el-table-column
          prop="code"
          label="变量CODE"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="" label="标签" align="center" width="180">
          <template slot-scope="scope">
            <!-- {{ $moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }} -->
            <el-tag
              style="margin: 2px"
              v-for="tag in scope.row.tagList"
              :key="tag.tagId"
            >
              {{ tag.tagName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            {{ $moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" align="center">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="最后修改"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            {{ $moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="修改人" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="160">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              style="color: red"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialog"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="addForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="变量名称" prop="text">
              <el-input
                v-model="addForm.text"
                placeholder="请输入变量名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="变量CODE" prop="code">
              <el-input
                v-model="addForm.code"
                placeholder="请输入变量CODE"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="变量标签" prop="tagIdList">
              <el-select
                style="width: 100%"
                multiple
                v-model="addForm.tagIdList"
                placeholder="请选择变量标签"
              >
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="填写类型" prop="operatorName">
              <el-select
                style="width: 100%"
                v-model="addForm.operatorName"
                placeholder="请选择变量填写类型"
                @change="changeOperator"
              >
                <el-option
                  v-for="item in dict.type.variable_input_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否必填" prop="required">
              <el-radio-group v-model="addForm.required">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          v-if="
            addForm.operatorName == 'radio' ||
            addForm.operatorName == 'checkbox' ||
            addForm.operatorName == 'select'
          "
        >
          <el-col :span="24">
            <el-form-item label="选项" prop="operatorName">
              <div class="row">
                <div class="row-1">序号</div>
                <div class="row-3">
                  选项
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    circle
                    style="margin-left: 8px"
                    @click="addOption"
                  ></el-button>
                </div>
              </div>
              <div
                class="row"
                v-for="(item, index) in addForm.optionsData"
                :key="index"
              >
                <div class="row-1">{{ index + 1 }}</div>
                <div class="row-3">
                  <el-input
                    style="width: 300px"
                    v-model="addForm.optionsData[index]"
                    placeholder="请输入内容"
                  ></el-input>
                  <el-button
                    type="text"
                    style="color: red; margin-left: 12px"
                    @click="delOption(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getListCode,
  insertCode,
  updateCode,
  deleteCode,
  getListTag,
  importData,
  exportData,
  exportDataTemplate,
} from "@/api/business/definition";
import { getToken } from "@/utils/auth";
export default {
  dicts: ["variable_input_type"],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selectionData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        param: {
          text: "",
          code: "",
          tagIdList: [],
        },
      },
      tagList: [],
      dataList: [],
      total: 0,
      title: "",
      addDialog: false,
      addForm: {
        name: "",
      },
      rules: {
        text: [{ required: true, message: "请输入变量名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入变量CODE", trigger: "blur" }],
      },
      // 变量导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（变量导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的变量数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + importData,
      },
    };
  },
  created() {
    this.getList();
    this.getTagList();
  },
  methods: {
    // 检测变量输入类型，判断是否添加选项框
    changeOperator(e) {
      // 判断是否为有选项的填写
      // 如果是, 则判断是否已经有options
      //        如果没有,则添加默认选项, 如果有,则直接显示不做修改
      // 在未点击缺点前,为防止操作失误,修改类型不删除options
      // 在最后点击提交时,如果填写类型不是以下三个, 删除options后再提交
      if (e == "radio" || e == "checkbox" || e == "select") {
        if (!this.addForm.optionList || !this.addForm.optionList.length) {
          // const optionList = ["选项一", "选项二"];
          const optionsData = ["选项一", "选项二"];
          this.addForm.optionsData = [...optionsData];
          this.$forceUpdate();
        } else {
          return;
        }
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        exportDataTemplate,
        {},
        `变量导入_${new Date().getTime()}.xlsx`
      );
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 导入数据
    handleImport() {
      this.upload.title = "变量导入";
      this.upload.open = true;
    },
    // 导出数据
    downloadData() {
      const that = this;
      this.$modal
        .confirm("是否确认导出当前查询条件下的数据？")
        .then(function () {
          // 导出
          const params = that.queryParams;
          return that.download(
            exportData,
            { ...params.param },
            `变量.xlsx`
          );
        })
        .then((res) => {
          that.$message.success("导出成功");
        })
        .catch(() => {});
    },
    // 获取标签数据列表
    getTagList() {
      const param = { ...this.queryParams };
      getListTag(param).then((response) => {
        console.log("response: ", response);
        this.tagList = response.data;
      });
    },
    // 搜索事件
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置事件
    resetQuery() {
      this.dataList = [];
      this.total = 0;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取数据列表
    getList() {
      this.loading = true;
      const param = { ...this.queryParams };
      getListCode(param).then((response) => {
        this.dataList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 列表选中事件
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selectionData = [...selection];
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 新增变量
    handleAdd() {
      this.title = "新增变量";
      this.addDialog = true;
    },
    // 新增/修改弹框提交事件
    async submitForm() {
      const param = { ...this.addForm };
      if (
        param.operatorName == "radio" ||
        param.operatorName == "checkbox" ||
        param.operatorName == "select"
      ) {
        if (param.optionsData.length) {
          param.options = JSON.stringify(this.arrayToObject(param.optionsData));
        } else {
          param.options = "";
        }
      } else {
        param.options = "";
      }
      if (param.id) {
        // 修改
        await updateCode(param).then((res) => {
          this.$message.success("修改成功");
          this.cancel();
          this.handleQuery();
        });
      } else {
        // 新增
        await insertCode(param).then((res) => {
          this.$message.success("新增成功");
          this.cancel();
          this.handleQuery();
        });
      }
    },
    arrayToObject(arr) {
      return arr.reduce((accumulator, currentValue, currentIndex) => {
        accumulator[currentIndex + 1] = currentValue;
        return accumulator;
      }, {});
    },
    // 新增/修改弹框取消事件
    cancel() {
      this.addForm = {
        text: "",
      };
      this.addDialog = false;
    },
    // 修改变量
    handleEdit(row) {
      this.title = "修改变量";
      const data = row.id ? row : this.selectionData[0];
      let optionList = [];
      if (data.options) {
        let optionsData = JSON.parse(data.options);
        optionList = Object.keys(optionsData).map((key) => optionsData[key]);
      }
      this.addForm = {
        ...data,
        text: data.name,
        id: data.id,
        tagIdList: data.tagList.map((item) => item.tagId),
        optionsData: optionList,
      };
      this.addDialog = true;
    },
    // 删除变量
    handleDelete(row) {
      const idList = row.id ? [row.id] : [...this.ids];
      this.$modal
        .confirm("是否确认删除当前选择的变量？")
        .then(function () {
          // 删除
          return deleteCode({ idList });
        })
        .then(() => {
          this.$message.success("删除成功");
          this.handleQuery();
        })
        .catch(() => {});
    },
    // 新增选项
    addOption() {
      const optionList = [...this.addForm.optionsData];
      optionList.push("");
      this.addForm.optionsData = [...optionList];
    },
    // 删除选项
    delOption(index) {
      const optionList = [...this.addForm.optionsData];
      optionList.splice(index, 1);
      this.addForm.optionsData = [...optionList];
    },
  },
};
</script>
<style lang="scss">
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.row-1 {
  width: 20%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.row-3 {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
